<template>
  <el-container direction="vertical" class="b">
    <blocks v-bind="{openFile, saveXml, ropenXml}"></blocks>
    <div id="top">
      <span v-text="text1"></span> &nbsp;
      <el-switch v-model="value2" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
      <setting></setting>
    </div>
  </el-container>
</template>

<script>
import { readFileSync } from "fs";
import { ipcRenderer } from "electron";
import blocks from "@/views/blocks.vue";
import setting from "@/components/setting.vue";
import { version } from "../package.json";
const Blockly = window.Blockly;
export default {
  name: "App",
  components: {
    blocks,
    setting
  },
  computed: {
    href() {
      return `/index.html?lang=${this.$i18n.locale}`;
    }
  },
  async mounted() {
    const { ropenXml } = this;
    document.title = `北京哈工科教DouBao编程软件_V${version}`;
    document.addEventListener("drop", e => {
      e.preventDefault();
      e.stopPropagation();

      let fileToUpload = e.dataTransfer.files[0];
      const getProjectTitleFromFilename = fileInputFilename => {
        if (!fileInputFilename) return "";
        const matches = fileInputFilename.match(/^(.*)\.xml?$/);
        if (!matches) return "";
        return matches[1].substring(0, 100); // truncate project title to max 100 chars
      };
      const uploadedProjectTitle = getProjectTitleFromFilename(
        fileToUpload.name
      );
      if (!uploadedProjectTitle) return;
      ropenXml(fileToUpload.path);
    });
    document.addEventListener("dragover", function(e) {
      e.preventDefault();
      e.stopPropagation();
    });
    ipcRenderer.on("file-path", (event, arg) => {
      if (arg) {
        this.ropenXml(arg);
      }
    });
    ipcRenderer.on("asynchronous-reply", (event, arg) => {
      console.log(arg);
      if (arg[0]) {
        this.$message.success(this.$t(arg[1]));
      } else {
        this.$message.error(this.$t(arg[1]));
      }
    });
  },
  watch: {
    value2() {
      window.location.href = this.href;
    }
  },
  methods: {
    async openFile() {
      ipcRenderer.send("open-file", "open-file");
    },
    async saveXml(name) {
      let xmlDom = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
      let xmlText = Blockly.Xml.domToPrettyText(xmlDom);
      if (
        xmlText ==
          '<xml xmlns="http://www.w3.org/1999/xhtml"><variables></variables></xml>' ||
        xmlText == '<xml xmlns="http://www.w3.org/1999/xhtml"></xml>'
      ) {
        this.$alert(this.$t("好像什么都没有"), this.$t("Tips"), {
          confirmButtonText: this.$t("Determine")
        });
        return;
      }
      ipcRenderer.send("saveXml", {
        name,
        text: xmlText
      });
    },
    async ropenXml(p) {
      let result = readFileSync(p, "utf8");
      let xml;
      try {
        xml = Blockly.Xml.textToDom(result);
        let blocks = xml.getElementsByTagName("block");
        for (let v of blocks) {
          const arr = ["propeller", "controls_dja", "fmq1"];
          if (arr.includes(v.attributes.type.value)) {
            for (let node of v.childNodes) {
              if (
                node.tagName === "field" &&
                node.attributes.name &&
                node.attributes.name["value"] === "NUM"
              ) {
                let block = this.createblock(
                  node.attributes.name.ownerElement.textContent
                );
                v.appendChild(block);
                v.removeChild(node);
              }
            }
          }
        }
      } catch (e) {
        this.$alert(this.$t("请选择一个.xml的文件") + e, this.$t("Tips"), {
          confirmButtonText: this.$t("Determine")
        });
        return false;
      }
      this.$confirm(this.$t("清空所有块, 是否继续?"), this.$t("Tips"), {
        confirmButtonText: this.$t("empty"),
        cancelButtonText: this.$t("cancel"),
        type: "warning"
      })
        .then(() => {
          Blockly.mainWorkspace.clear();
          Blockly.Xml.appendDomToWorkspace(xml, Blockly.mainWorkspace);
          // const tab_blocks = document.getElementById("tab_blocks");
          // 保存文件路径
          // baseURI = p;
          setTimeout(function() {
            Blockly.mainWorkspace.undo(0);
            Blockly.mainWorkspace.undo(1);
          });
          return true;
        })
        .catch(e => {
          console.log(e);
          this.$message({
            type: "info",
            message: this.$t("文件已损坏")
          });
          return false;
        });
    },
    createblock(num) {
      return Blockly.Xml.textToDom(
        `<value name="NUM"><shadow type="math_number"><field name="NUM">${num}</field></shadow></value>`
      );
    }
  },
  data() {
    const text1 = this.$t("Stage");
    return {
      value2: true,
      text1,
      lang: ""
    };
  }
};
</script>

<style>
* {
  margin: 0;
  padding: 0;
}
.b {
  height: 100%;
}
#top {
  position: absolute;
  top: 12px;
  right: 14px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 0.75rem;
  font-weight: bold;
  color: hsla(0, 100%, 100%, 1);
}
</style>
